package com.tarena.lbs.basic.web.service;

import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.basic.web.repository.UserRepository;
import com.tarena.lbs.common.basic.util.RandomUserName;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.common.security.utils.LbsSecurityContenxt;
import com.tarena.lbs.pojo.basic.param.UserParam;
import com.tarena.lbs.pojo.basic.po.UserPO;
import com.tarena.lbs.pojo.basic.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    public void doRegister(UserParam param) throws BusinessException {
        //1.校验手机号是否存在 查询存在 如果存在则抛异常 幂等拦截

        String phone=param.getPhone();
        long total=userRepository.countByPhone(phone);
        Asserts.isTrue(total>0,new BusinessException("-2","手机号已经存在"));
        //2.封装数据 随机一个nickname
        String randomName = RandomUserName.createRandomName();
        UserPO poParam=new UserPO();
        BeanUtils.copyProperties(param,poParam);
        //剩余属性 status=0没有绑定标签 username nickname reg_time注册时间
        poParam.setStatus(0);
        poParam.setUserName(randomName);
        poParam.setNickName(randomName);
        poParam.setRegTime(new java.util.Date());
        //3.持久层写入
        userRepository.saveUser(poParam);
    }

    public UserVO userDetail() throws BusinessException {
        UserPrinciple userPrinciple = LbsSecurityContenxt.getLoginToken();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证失败"));
        Integer id = userPrinciple.getId();
        UserPO po=userRepository.getUserById(id);
        Asserts.isTrue(po==null||po.getId()==null,
                new BusinessException("-2","用户信息不存在"));
        UserVO vo=new UserVO();
        BeanUtils.copyProperties(po,vo);
        return vo;
    }
}
